package com.bite.order.service;

import com.bite.order.mapper.OrderMapper;
import com.bite.order.model.OrderInfo;
import com.bite.order.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    private AtomicInteger count = new AtomicInteger(1);

    List<ServiceInstance> instances;
    @PostConstruct
    private void init() {
        // 防止每一次获取不一样导致轮询有差异
        instances = discoveryClient.getInstances("product-service");
    }

    // restTemplate
    public OrderInfo selectById1(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);

//        String url = "http://localhost:9090/product/" + orderInfo.getProductId();
        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        String uri = instances.get(0).getUri().toString();
        String url = uri + "/product/" + orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }


    // instances
    public OrderInfo selectById2(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);

        // 轮询并自增
        int index = count.getAndIncrement() % instances.size();
        String uri = instances.get(index).getUri().toString();
        String url = uri + "/product/" + orderInfo.getProductId();
        log.info("获取url {}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }

    // 负载均衡
    public OrderInfo selectById(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectById(orderId);

        String url = "http://product-service/product/" + orderInfo.getProductId();
        log.info("获取url {}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }

}
